import { EventManager, MyEvent } from "./Framework/Managers/EventManager";
import { EasingType } from "./Framework/Utils/TweenUtil";
import { ZTool } from "./Framework/Utils/ZTool";
import GameManager from "./GameManager";

const { ccclass, property } = cc._decorator;

const v2_0: cc.Vec2 = cc.v2();
const v2_1: cc.Vec2 = cc.v2();
const v2_2: cc.Vec2 = cc.v2();
const v2_3: cc.Vec2 = cc.v2();

@ccclass
export default class CameraController extends cc.Component {
    static Instance: CameraController = null;
    camera: cc.Camera = null;
    stopFollow: boolean = false;

    onLoad() {
        CameraController.Instance = this;
        this.camera = this.node.getComponent(cc.Camera);
    }

    Move(delta: cc.Vec2) {
        this.stopFollow = true;
        this.node.getPosition(v2_3);
        v2_3.addSelf(delta.negate().multiplyScalar(5))
        v2_3.set(cc.v2(ZTool.Clamp(v2_3.x, -5000, 5000), ZTool.Clamp(v2_3.y, -5000, 5000)));
        this.node.setPosition(v2_3);
    }

    ZoomIn() {
        cc.Tween.stopAllByTarget(this.camera);
        cc.tween(this.camera).to(0.2, { zoomRatio: 1 }, { easing: EasingType.quadIn }).start();
    }

    ZoomOut(ratio: number = 0.5) {
        cc.Tween.stopAllByTarget(this.camera);
        cc.tween(this.camera).to(0.2, { zoomRatio: ratio }, { easing: EasingType.quadIn }).start();
    }

    update(dt) {
        if (this.stopFollow) return;
        if (!GameManager.Instance.player) return;
        this.node.getPosition(v2_0);
        GameManager.Instance.player.getPosition(v2_1);
        cc.Vec2.lerp(v2_2, v2_0, v2_1, 0.2);
        this.node.setPosition(v2_2);
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.CameraZoomIn, this.ZoomIn, this);
        EventManager.on(MyEvent.CameraZoomOut, this.ZoomOut, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.CameraZoomIn, this.ZoomIn, this);
        EventManager.off(MyEvent.CameraZoomOut, this.ZoomOut, this);
    }
}
